package menu

import (
	"context"
	"database/sql"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"
)

type UpdateMenuLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMenuLogic {
	return &UpdateMenuLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateMenuLogic) UpdateMenu(in *pb.UpdateMenuReq) (*pb.EmptyObj, error) {
	// 1.菜单非法性校验
	menuMapper := mapper.NewMenuMapper()
	checkErr := l.checkMenu(in, menuMapper)
	if checkErr != nil {
		return nil, checkErr
	}
	// 2.保存DB
	menuEntity := entity.SysMenuEntity{
		ParentId: sql.NullInt64{Int64: in.ParentId, Valid: true}, Name: in.Name, Url: in.Url,
		Perms: in.Perms, Type: sql.NullInt16{Int16: int16(in.MenuType), Valid: true}, Icon: in.Icon,
		OrderNum: sql.NullInt32{Int32: in.OrderNum, Valid: true},
	}
	updateErr := menuMapper.UpdateMenuByMenuId(l.svcCtx.DBEngin, menuEntity)
	if updateErr != nil {
		return nil, updateErr
	}
	// 3.返回参数
	return &pb.EmptyObj{}, nil
}

func (l *UpdateMenuLogic) checkMenu(in *pb.UpdateMenuReq, menuMapper *mapper.MenuMapper) error {
	count, existErr := menuMapper.SelectCount(l.svcCtx.DBEngin, bo.SysMenuBO{
		MenuId: in.MenuId,
	})
	if existErr != nil {
		return existErr
	}
	if count != 1 {
		return excption.NewErrCode(constans.MenuNoExistError)
	}
	// 1.2 other check
	saveMenuLogic := NewSaveMenuLogic(l.ctx, l.svcCtx)
	saveReq := new(pb.SaveMenuReq)
	copyErr := copier.Copy(saveReq, in)
	if copyErr != nil {
		return copyErr
	}
	checkErr := saveMenuLogic.doCheckMenu(saveReq, menuMapper)
	if checkErr != nil {
		return checkErr
	}
	return nil
}
